package com.my.house.service;

import com.my.house.common.utils.ThreadLocalHolder;
import com.my.house.domain.Building;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import com.my.house.mapper.BuildingMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 楼栋信息表 服务实现类
 * </p>
 *
 * @author yangll
 * @since 2025-02-08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BuildingService extends ServiceImpl<BuildingMapper, Building> {
    private final RoomService roomService;

    /**
     * 根据用户id查询楼栋列表
     * @param userId 用户id
     * @return 用户的楼栋列表
     */
    public List<Building> findByUserId(Long userId) {
        Long localUserId = ThreadLocalHolder.getUserId();
        log.info("localUserId = {}, findByUserId方法参数:{}", localUserId, userId);
        return lambdaQuery().eq(Building::getUserId,userId).eq(Building::getDeleted, Boolean.FALSE).list();
    }

    /**
     * 新增楼栋信息
     * @param userId 用户id
     * @param name 楼栋名称
     * @param address 楼栋地址
     */
    public void addBuilding(Long userId, String name, String address) {
        Building building = new Building();
        building.setUserId(userId);
        building.setName(name);
        building.setAddress(address);
        save(building);
    }

    /**
     * 根据id修改楼栋信息
     * @param id 楼栋id
     * @param name 楼栋名称
     * @param address 楼栋地址
     */
    public void editBuildingById(Long userId, Long id, String name, String address) {
        assert id != null;
        lambdaUpdate().eq(Building::getId, id).eq(Building::getUserId, userId)
                .set(Objects.nonNull(name), Building::getName, name)
                .set(Objects.nonNull(address), Building::getAddress, address)
                .update();
    }

    /**
     * 根据id删除楼栋信息
     * @param userId 用户id
     * @param id 楼栋id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteBuildingById(Long userId, Long id) {
        assert id != null;
        lambdaUpdate().eq(Building::getId, id)
                .eq(Building::getUserId, userId)
                .set(Building::getDeleted, Boolean.TRUE)
                .update();
        // 删除楼栋的所有房间
        roomService.deleteRoomByBuildingId(userId, id);
    }
}
